package com.copractice.bl.signin;

import org.hibernate.Transaction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.copractice.data.dao.hibernate.util.DBUtils;
import com.copractice.data.dao.user.UserDAO;
import com.copractice.data.entity.user.User;
import com.google.inject.Inject;

/**
 * Contains business logic methods for sign in operation.
 * 
 * @author Dmitry Churbanov (dmitry.churbanov@gmail.com)
 * @version 1.0 01/01/2010
 */
public class SignInBL {
    
    private static final Logger LOG = LoggerFactory.getLogger(SignInBL.class);
    
    private UserDAO userDAO;
    
    @Inject
    public void setUserDAO(UserDAO userDAO) {
        this.userDAO = userDAO;
    }
    
    public UserDAO getUserDAO() {
        return userDAO;
    }

    /**
     * Checks if <code>username</code> and <code>password</code> matches the record in db. 
     * 
     * @param userName name of a user
     * @param password users password
     * 
     * @return true if the record with the <code>username</code> and <code>password</code> was found in the db. 
     *              Otherwise returns false.
     *               
     */
    public User getValidUser(String userName, String password) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Checks user : '{}'; with password: '{}'", userName, password);
        }
        
        Transaction tx = null;
        User user = null;
        try {
            tx = DBUtils.beginTransaction();
            
            user = getUserDAO().findByUserName(userName);
            tx.commit();
        } catch (RuntimeException ex) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Rollback the transaction: username = {}", userName);
            }
            tx.rollback();
            if (LOG.isDebugEnabled()) {
                throw new RuntimeException(ex);
            }
        }
        
        //TODO Change to encrypted password
        return user != null && user.getPassword().equals(password) ? user : null; 
    }
}
